package com.sgj.handler;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePrecreateRequest;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.sgj.enums.PayTypeEnum;
import com.sgj.utils.QrCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;

/**
 * 支付宝支付（native）
 * @author 沈国纪
 * @date 2022/1/3 15:51
 */
@Slf4j
@Component
public class AliNativeHandler extends AbstractHandler {

	@Value("${alipay.appid}")
	public String ALI_APPID;
	@Value("${alipay.alipayPublicKey}")
	public String ALI_ALIPAYPUBLICKEY;
	@Value("${alipay.privateKey}")
	public String ALI_PRIVATEKEY;
	@Value("${alipay.notifyUrl}")
	public String ALI_NOTIFY_URL;

	@Override
	public void pay(String orderName, String orderNo, BigDecimal amount, HttpServletResponse response) throws AlipayApiException {
		AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", ALI_APPID,
				ALI_PRIVATEKEY, "json", "UTF-8", ALI_ALIPAYPUBLICKEY, "RSA2");
		// 创建 API 对应的 request 类
		AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
		// 传入指定参数，具体根据官方文档
		JSONObject bizContent = new JSONObject();
		bizContent.put("out_trade_no", orderNo);
		bizContent.put("total_amount", amount);
		bizContent.put("subject", orderName);

		request.setBizContent(bizContent.toString());
		request.setNotifyUrl(ALI_NOTIFY_URL);
		AlipayTradePrecreateResponse alipayTradePrecreateResponse = alipayClient.execute(request);
		log.info("[AliNativeHandler][pay] 支付宝支付请求发送成功:{}", JSONObject.toJSONString(alipayTradePrecreateResponse.getBody()));

		// 解析回调 url
		String qcCode = JSONObject.parseObject(JSONObject.parseObject(alipayTradePrecreateResponse.getBody())
				.getString("alipay_trade_precreate_response")).getString("qr_code");

		// 生成二维码
		QrCodeUtil.createQrCodeByUrl(qcCode, response);
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		Factory.register(PayTypeEnum.ALI_NATIVE, this);
	}
}